var shopConfigurationTableInit = function(){
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#shopConfigurationTable').bootstrapTable({
            url: ctx +'/equipment/configuration/threed/listConfigurationByFilter/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop:false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect:false,                    //禁止多选
            checkboxHeader:true,                 //列头取消多选
            columns: [
                {
                    checkbox:true,
                    align : 'center',
                    valign : 'middle'
                },
                {
                    title: '序号',
                    align : 'center',
                    valign : 'middle',
                    formatter : function (value, row, index){
                        var options = $('#shopConfigurationTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                },
                {
                    field: 'code',
                    title: '组态编码',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'name',
                    title: '组态名称',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                }, {
                    field: 'factoryName',
                    title: '所属厂区',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                }, {
                    field: 'shopCode',
                    title: '车间编码',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'shopName',
                    title: '车间名称',
                    sortable:false,
                    align : 'center',
                    valign : 'middle',
                }, {
                    field: 'operation',
                    title: '包含工序',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                }, {
                    field: '',
                    title: '组态管理',
                    sortable:false,
                    align : 'center',
                    valign : 'middle',
                    formatter : function (value, row, index){
                    	return "<a href='javascript:;' class='click_btn design' data-id='"+row.pkId+"' >组态设计</a>"+
                        "<a href='javascript:;' class='click_btn monitor' data-id='"+row.pkId+"'>车间监控</a>";
                    }
                }, {
                    field: 'pkId',
                    title: 'pkId',
                    visible:false
                }]

        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            code: $("#code").val(),
            factoryId: $("#factory").val(),
            locationId: $("#shop").val(),
            type:'3'
        };
    };
    return oTableInit;
};

jQuery(document).ready(function() {
    //1.初始化Table
    var oTable = new shopConfigurationTableInit();
    oTable.Init();
    //初始化页面
    shopConfigutationInit.init();
});




var shopConfigutationInit = function() {
    return {
        init:function() {
            shopConfigutationInit._query();
            shopConfigutationInit._keyQuery();
            shopConfigutationInit._reset();
            shopConfigutationInit._refresh();
            shopConfigutationInit._add();
            shopConfigutationInit._update();
            shopConfigutationInit._delete();
            shopConfigutationInit._validatorForm();
            shopConfigutationInit._initFactorySelect();
            shopConfigutationInit._initShopSelect();
            shopConfigutationInit._initFactorySelectChange();
            shopConfigutationInit._initShopSelectChange();
            shopConfigutationInit._initQueryFactorySelect();
            shopConfigutationInit._initQueryShopSelect();
            shopConfigutationInit._initQueryFactorySelectChange();
            shopConfigutationInit._initQueryShopSelectChange();
            shopConfigutationInit._save();
            shopConfigutationInit._modalHidden();
            shopConfigutationInit._configurationButton();
        },
        //条件查询
        _query:function() {
            $("#queryconfiguration").on("click",function(){
                $('#shopConfigurationTable').bootstrapTable('refreshOptions',{
                    pageNumber:1
                });
            });
        },
        //按键查询
        _keyQuery:function() {
            $(".configurationQuery").keypress(function (e) {
                if (e.which === 13) {
                    $("#queryconfiguration").trigger("click");
                }
            });
        },
        //重置查询
        _reset:function() {
            $(".reset").on("click",function(){
                $(".clearfix input").val("");
                //重置select2选择框
                $(".clearfix select").val("");
                shopConfigutationInit._initQueryShopSelect();
            });
        },
        _refresh : function(){
            //刷新
            $("#refreshTable").on("click",function(){
                $('#shopConfigurationTable').bootstrapTable('refresh');
            });
        },
        //新增
        _add : function() {
            $("#add").on('click', function(e) {
                e.preventDefault();
                $('#myModal .title').html("新增");
                $("#myModal").modal();
            });
        },
        _initQueryFactorySelect : function () {
            $.ajax({
                url: ctx +'/factory/factoryArea/listAllFactory/get.mvc',
                type:"post",
                aysnc: true,
                dataType:'json',
                data : '',
                success : function(data){
                    $("#factory").append("<option value='' >请选择</option>");
                    for (var i = 0; i < data.length; i++) {
                        $("#factory").append("<option value='"+data[i].pkId+"' >" + data[i].factoryName + "</option>");
                    }
                },
                error: function(){
                    alert("加载厂区下拉框出错");
                }
            });

        },
        _initQueryShopSelect : function () {
            $("#shop").empty();
            $.ajax({
                url: ctx +'/factory/shop/listAllShopsByFactoryId/get.mvc',
                type:"post",
                aysnc: true,
                dataType:'json',
                success : function(response){
                    if(response.result === true) {
                        var _data = response.data;
                        $("#shop").append("<option value='' >请选择</option>");
                        for (var i = 0; i < _data.length; i++) {
                            $("#shop").append("<option value='"+_data[i].pkId+"' >" + _data[i].shopName + "</option>");
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error: function(){
                    alert("加载车间下拉框出错");
                }
            });
        },
        _initQueryFactorySelectChange : function () {
            //厂区车间联动
            console.log("factory select init change event");
            $("#factory").off("change").on("change",function () {
                console.log("factory select value change ");
                $("#shop").val("");
                $("#shop").empty();
                var factoryId = $(this).val();
                $.ajax({
                    url: ctx +'/factory/shop/listAllShopsByFactoryId/get.mvc',
                    type:"post",
                    aysnc: false,
                    dataType:'json',
                    data : {
                        factoryId:factoryId
                    },
                    success : function(response){
                        //debugger
                        if(response.result === true) {
                            var _data = response.data;
                            $("#shop").append("<option value='' >请选择</option>");
                            for (var i = 0; i < _data.length; i++) {
                                $("#shop").append("<option value='"+_data[i].pkId+"' >" + _data[i].shopName + "</option>");
                            }
                        } else {
                            DialogUtil.error(response.message);
                        }

                    },
                    error: function(){
                        alert("系统错误3");
                    }
                });
            });
        },
        _initQueryShopSelectChange : function () {
            //厂区车间联动
            $("#shop").on("change",function () {
                //接触onchange绑定事件
                $("#factory").off("change");
                console.log("factory select off change...")
                var shopId = $(this).val();
                $.ajax({
                    url: ctx +'/factory/shop/getShopById/get.mvc',
                    type:"post",
                    aysnc: false,
                    dataType:'json',
                    data : {
                        pkId:shopId
                    },
                    success : function(response){
                        //debugger
                        $("#factory").val(response.factoryId);
                    },
                    error: function(){
                        alert("系统错误4");
                    }
                });
                shopConfigutationInit._initQueryFactorySelectChange();
            });

        },
        _initFactorySelect : function () {
            $.ajax({
                url: ctx +'/factory/factoryArea/listAllFactory/get.mvc',
                type:"post",
                aysnc: true,
                dataType:'json',
                data : '',
                success : function(data){
                    $("#shopConfigurationForm select[name=factory]").append("<option value='' >请选择</option>");
                    for (var i = 0; i < data.length; i++) {
                        $("#shopConfigurationForm select[name=factory]").append("<option value='"+data[i].pkId+"' >" + data[i].factoryName + "</option>");
                    }
                },
                error: function(){
                    alert("系统错误1");
                }
            });

        },

        //加载车间下拉列表
        _initShopSelect : function () {
            $.ajax({
                url: ctx +'/factory/shop/listAllShopsByFactoryId/get.mvc',
                type:"post",
                aysnc: true,
                dataType:'json',
                success : function(response){
                    if(response.result === true) {
                        var _data = response.data;
                        $("#shopSelect").append("<option value='' >请选择</option>");
                        for (var i = 0; i < _data.length; i++) {
                            $("#shopSelect").append("<option value='"+_data[i].pkId+"' >" + _data[i].shopCode + "</option>");
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error: function(){
                    alert("系统错误2");
                }
            });

        },
        _initFactorySelectChange : function () {
            //厂区车间联动
            console.log("factory select init change event");
            $("#factorySelect").off("change").on("change",function () {
                console.log("factory select value change ");
                $("#shopSelect").val("");
                $("#shopSelect").empty();
                $('#shopConfigurationForm').bootstrapValidator('resetForm', false);
                var factoryId = $(this).val();
                $.ajax({
                    url: ctx +'/factory/shop/listAllShopsByFactoryId/get.mvc',
                    type:"post",
                    aysnc: false,
                    dataType:'json',
                    data : {
                        factoryId:factoryId
                    },
                    success : function(response){
                        //debugger
                        if(response.result === true) {
                            var _data = response.data;
                            $("#shopSelect").append("<option value='' >请选择</option>");
                            for (var i = 0; i < _data.length; i++) {
                                $("#shopSelect").append("<option value='"+_data[i].pkId+"' >" + _data[i].shopCode + "</option>");
                            }
                            $("#shopConfigurationForm input[name=operation]").val("");
                            $("#shopConfigurationForm input[name=shopName]").val("");
                        } else {
                            DialogUtil.error(response.message);
                        }

                    },
                    error: function(){
                        alert("系统错误3");
                    }
                });
            });
        },
        _initShopSelectChange : function () {
            //厂区车间联动
            $("#shopSelect").on("change",function () {
                //接触onchange绑定事件
                $("#factorySelect").off("change");
                console.log("factory select off change...");
                $('#shopConfigurationForm').bootstrapValidator('resetForm', false);
                var shopId = $(this).val();
                $.ajax({
                    url: ctx +'/factory/shop/getShopById/get.mvc',
                    type:"post",
                    aysnc: false,
                    dataType:'json',
                    data : {
                        pkId:shopId
                    },
                    success : function(response){
                        //debugger
                        $("#factorySelect").val(response.factoryId);
                        $("#shopConfigurationForm input[name=operation]").val(response.operationName);
                        $("#shopConfigurationForm input[name=shopName]").val(response.shopName);
                    },
                    error: function(){
                        alert("系统错误4");
                    }
                });
                shopConfigutationInit._initFactorySelectChange();
            });

        },
        //删除
        _delete : function () {
            $("#delete").on("click", function(){
                var ids = $.map($('#shopConfigurationTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length <1 ) {
                    DialogUtil.warning("请选择需要删除的记录");
                    return false;
                }
                DialogUtil.ok_and_cancel("是否确定删除记录？",function(){
                    $.ajax({
                        url: ctx + '/equipment/configuration/threed/deleteConfiguration/del.mvc',
                        type:"post",
                        dataType:'json',
                        data : {
                            pkIds : ids.toString()
                        },
                        success : function(response){
                            console.log(response);
                            if (response.result === true) {
                                DialogUtil.warning("删除成功");
                                $('#shopConfigurationTable').bootstrapTable('refresh');
                            }else {
                                DialogUtil.error(response.message);
                            }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown){
                            DialogUtil.error(errorThrown);
                        }
                    });
                },function(){

                });
            });
        },
        //修改
        _update : function () {
            $("#update").on("click",function (e) {
                e.preventDefault();
                $('#myModal .title').html("修改");
                var ids = $.map($('#shopConfigurationTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length !== 1 ) {
                    DialogUtil.warning("请选择一行修改");
                    return false;
                }
                //加载信息
                $.ajax({
                    url: ctx+"/equipment/configuration/threed/getConfigurationById/get.mvc",
                    type: "post",
                    dataType: "json",
                    async : false,
                    data:{
                        pkId:ids.toString()
                    },
                    success :function(response) {
                        if(response.result === true&&response.data) {
                            var _data = response.data;
                            $("#shopConfigurationForm").find("input[name=pkId]").val(_data.pkId);
                            $("#shopConfigurationForm").find("input[name=code]").val(_data.code);
                            $("#shopConfigurationForm").find("input[name=name]").val(_data.name);
                            $("#shopConfigurationForm").find("input[name=shopName]").val(_data.shopName);
                            $("#shopConfigurationForm").find("select[name=factory]").val(_data.factoryId);
                            $("#shopConfigurationForm").find("select[name=shop]").val(_data.shopId);
                            $("#shopConfigurationForm").find("input[name=operation]").val(_data.operation);
                            $('#myModal').modal();

                        } else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error :function() {
                        DialogUtil.error("系统繁忙！");
                    }
                });

            });
        },
        //表单校验
        _validatorForm : function () {
            $("#shopConfigurationForm").bootstrapValidator({
                message: 'This value is not valid',
                live: 'submitted',
                fields: {/*验证*/
                    code: {
                        message: '组态编码无效',
                        validators: {
                            notEmpty: {
                                message: '组态编码不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '组态编码长度不能超过20个字符'
                            }
                        }/*,
                        threshold: 11, //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
                        remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}
                            url: '/Login/CheckUserTelephoneEmail',//验证地址
                            data:{documentCode:$('input[name="usertelephone"]').val() }
                        },message: '手机号已被注册',//提示消息
                        delay: 2000,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
                        type: 'POST'//请求方式
                        },*/
                    },
                    name: {
                        message: '组态名称无效',
                        validators: {
                            notEmpty: {
                                message: '组态名称不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '组态名称不能超过20个字符'
                            }
                        }
                    },
                    shop: {
                        message: '车间编号无效',
                        validators: {
                            notEmpty: {
                                message: '车间编号不能为空'
                            }
                        }
                    },
                    shopName: {
                        message: '车间名称无效',
                        validators: {
                            notEmpty: {
                                message: '车间名称不能为空'
                            }
                        }
                    },
                    operation: {
                        message: '工序无效',
                        validators: {
                            notEmpty: {
                                message: '工序不能为空'
                            }
                        }
                    }


                }
            });
        },
        //保存
        _save : function () {
            $("#myModal .yes").on("click",function (e) {
                e.preventDefault();
                $("#shopConfigurationForm").data("bootstrapValidator").validate();
                var flag = $("#shopConfigurationForm").data("bootstrapValidator").isValid();
                if(!flag){
                    //未通过验证
                    return false;
                }
                $("#myModal .yes").attr("disabled",true);
                var entity = {};
                entity['pkId'] = $("#shopConfigurationForm").find("input[name=pkId]").val();
                entity['code'] = $("#shopConfigurationForm").find("input[name=code]").val();
                entity['name'] = $("#shopConfigurationForm").find("input[name=name]").val();
                entity['locationId'] = $("#shopConfigurationForm").find("select[name=shop]").val();
                entity['type'] = '3';
                $.ajax({
                    url : ctx + '/equipment/configuration/threed/saveOrUpdateConfiguration/save.mvc',
                    type : "post",
                    dataType : 'json',
                    data : entity,
                    success : function(response) {
                        if (response.result === true) {
                            DialogUtil.ok("保存成功");
                            //取消
                            $('#myModal').modal('hide');
                            $('#shopConfigurationTable').bootstrapTable('refresh');
                        } else {
                            DialogUtil.error(response.message);
                        }
                        $("#myModal .yes").attr("disabled",false);

                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#myModal .yes").attr("disabled",false);
                        console.log(errorThrown);
                        DialogUtil.error("系统错误");
                    }
                });

            });
        },
        _modalHidden : function () {
            //模态框消失清空信息
            $("#myModal").on("hide.bs.modal",function(e){
                $('#myModal input').each(function() {
                    if ($(this).val() !== "" || $(this).prop('checked') === true) {
                        $(this).val("").prop('checked', false);
                    }
                });
                //重新加载下拉框
                $("#factorySelect").empty();
                $("#shopSelect").empty();
                shopConfigutationInit._initFactorySelect();
                shopConfigutationInit._initShopSelect();
                $("#myModal select").each(function () {
                    $(this).val("");
                });
                $('#shopConfigurationForm').bootstrapValidator('resetForm', false);
            });
        },
        _configurationButton : function(){
        	//组态设计事件
        	$(document).on("click",".design",function(){
        		debugger;
        		var id =$(this).data("id");
        		window.location.href=ctx+"/equipment/configuration/threed/design/index?type=3&fileKey="+id;
//        		window.open(ctx+"/equipment/configuration/threed/design/index?type=3&fileKey="+id);
        	});
        	$(document).on("click",".monitor",function(){
        		var id =$(this).data("id");
        		window.location.href=ctx+"/equipment/configuration/threed/monitor/index?type=3&fileKey="+id;
//        		window.open(ctx+"/equipment/configuration/threed/design/index?type=3&fileKey="+id);
        	});
        }
    }
}();